{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 327,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at\n",
    "https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "FLAGS = None\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的Mnist数据函数为我们读入数据，如果没有下载的话则进行下载。\n",
    "\n",
    "<font color=#ff0000>**这里将data_dir改为适合你的运行环境的目录**</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 328,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting /home/pxt/datasets/MNIST/train-images-idx3-ubyte.gz\n",
      "Extracting /home/pxt/datasets/MNIST/train-labels-idx1-ubyte.gz\n",
      "Extracting /home/pxt/datasets/MNIST/t10k-images-idx3-ubyte.gz\n",
      "Extracting /home/pxt/datasets/MNIST/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "data_dir = '/home/pxt/datasets/MNIST'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个非常非常简陋的模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 更改隐层数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 329,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "#layer 1\n",
    "x = tf.placeholder(tf.float32, [None, 784])   #不确定多少个batch，784由mnist数据决定，像素点个数：28×28=784\n",
    "W1 = tf.Variable(tf.truncated_normal([784, 256]))       #修改权重初始化方式\n",
    "b1 = tf.Variable(tf.zeros([256]))\n",
    "y1 = tf.matmul(x, W1) + b1               #注意x，w的顺序\n",
    "logit1 = tf.nn.relu(y1)\n",
    "\n",
    "#layer 2\n",
    "W2 = tf.Variable(tf.truncated_normal([256, 128]))       #修改权重初始化方式\n",
    "b2 = tf.Variable(tf.zeros([128]))\n",
    "y2 = tf.matmul(logit1, W2) + b2               #注意x，w的顺序\n",
    "logit2 = tf.nn.relu(y2)\n",
    "\n",
    "#layer 2\n",
    "W3 = tf.Variable(tf.zeros([128, 10]))       #修改权重初始化方式\n",
    "b3 = tf.Variable(tf.zeros([10]))\n",
    "y = tf.matmul(logit2, W3) + b3               #注意x，w的顺序\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义我们的ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 330,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])     #数据中的标准值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits的logits参数是**未经激活的wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 334,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)+tf.contrib.layers.l2_regularizer(0.001)(W1)+tf.contrib.layers.l2_regularizer(0.001)(W2)+tf.contrib.layers.l2_regularizer(0.001)(W3))     #使用logits来计算交叉熵的方法，使用这个函数时注意一定不能经过激活\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 335,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)\n",
    "\n",
    "sess = tf.Session()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个batch。\n",
    "然后我们运行3k个step(5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 336,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "accuracy: 0.8866\n",
      "accuracy: 0.9136\n",
      "accuracy: 0.9277\n",
      "accuracy: 0.9374\n",
      "accuracy: 0.9426\n",
      "accuracy: 0.9481\n",
      "accuracy: 0.9528\n",
      "accuracy: 0.9559\n",
      "accuracy: 0.9581\n",
      "accuracy: 0.9612\n",
      "accuracy: 0.9638\n",
      "accuracy: 0.9662\n",
      "accuracy: 0.97\n",
      "accuracy: 0.972\n",
      "accuracy: 0.9733\n",
      "accuracy: 0.9745\n",
      "accuracy: 0.9757\n",
      "accuracy: 0.9767\n",
      "accuracy: 0.9769\n",
      "accuracy: 0.9773\n",
      "accuracy: 0.9783\n",
      "accuracy: 0.9793\n",
      "accuracy: 0.9793\n",
      "accuracy: 0.9796\n",
      "accuracy: 0.9795\n",
      "accuracy: 0.9798\n",
      "accuracy: 0.9803\n",
      "accuracy: 0.9808\n",
      "accuracy: 0.9809\n",
      "accuracy: 0.9812\n",
      "accuracy: 0.9811\n",
      "accuracy: 0.9805\n",
      "accuracy: 0.9813\n",
      "accuracy: 0.9817\n",
      "accuracy: 0.9821\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "i=0\n",
    "for _ in range(420000):\n",
    "    i+=1\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)    #每次得到100张图片\n",
    "    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    if i%12000 == 0:    #每20个epoch输出一次测试精度\n",
    "          # Test trained model\n",
    "        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(\"accuracy:\",sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                              y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
